package com.lee.query;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/3/10
 */
public class AggsQuery {
    private static RestHighLevelClient client;
    @BeforeAll
    public static void init() {
        client = new RestHighLevelClient(RestClient.builder(HttpHost.create("https://elasticsearch-dev.souban.io")));
    }
    @AfterAll
    private static void destory() throws IOException {
        client.close();
    }

    @Test
    public void maxQuery() throws IOException {
        final SearchRequest request = new SearchRequest();
        request.indices("user");


        final MaxAggregationBuilder maxAge = AggregationBuilders.max("MaxAge").field("age");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.aggregation(maxAge);
        searchSourceBuilder.size(0);
        request.source(searchSourceBuilder);

        final SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        searchResponse.getAggregations().asList().forEach(i -> System.out.println(i.getMetadata()));
    }
}
